/**
 *@Title: NIOChannelServer.java
 *@Description: TODO
 *@author:Lau
 *@date 2017年7月9日 下午4:45:00 
 *@version V1.0
 */
package com.lty.nio.channeltest;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.SocketChannel;

/** 
* @ClassName: NIOChannelServer 
* @Description: 通道实例客户端
* @author Lau 
* @date 2017年7月9日 下午4:45:00 
*  
*/
public class NIOChannelClient {
	private ByteBuffer buff = ByteBuffer.allocate(8);
	
	//创建一个int型buffer缓冲区视图，此视图的改变和buff是同步的，彼此可见
	private IntBuffer intBuff = buff.asIntBuffer();
	
	private SocketChannel channel = null;
	
	/***
	 * 
	* @Title: connect 
	* @Description: 与服务器指定的地址和端口建立连接
	* @return
	* @throws Exception
	* SocketChannel
	* @throws
	 */
	public SocketChannel connect() throws Exception{
		return SocketChannel.open(new InetSocketAddress("127.0.0.1", 8888));
	}
	
	/***
	 * 
	* @Title: getSum 
	* @Description: 获得加法运算结果
	* @param a
	* @param b
	* @return
	* @throws Exception
	* int
	* @throws
	 */
	public int getSum(int a, int b) throws Exception{
		int result = 0;
		channel = connect();
		sendRequest(a,b);
		
		result = receiveResult();
		return result;
	}
	
	/***
	 * 
	* @Title: receiveResult 
	* @Description: 接收服务器运行结果
	* @return
	* @throws Exception
	* int
	* @throws
	 */
	private int receiveResult() throws Exception{
		buff.clear();
		channel.read(buff);
		return intBuff.get(0);
	}

	/***
	 * 
	* @Title: sendRequest 
	* @Description: 发送请求到服务器
	* @param a
	* @param b
	* @throws Exception
	* void
	* @throws
	 */
	private void sendRequest(int a, int b) throws Exception{
		buff.clear();
		intBuff.put(0, a);
		intBuff.put(1, b);
		channel.write(buff);
		System.out.println("发送加法请求：(" + a + " + " + b + ")");
	}

	public static void main(String[] args) throws Exception {
		int result = new NIOChannelClient().getSum(32, 68);
		System.out.println("加法运算的最终结果：" + result);
	}
	
}
